# coding:utf-8
import os
from PIL import Image, ImageDraw, ImageFont


def add_text_to_image(imagefile, text, savefilename):
    image = Image.open(imagefile)
    font = ImageFont.truetype('C:\Windows\Fonts\STXINGKA.TTF', 36)
    # 添加背景
    new_img = Image.new(
        'RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
    new_img.paste(image, image.size)
    # 添加水印
    font_len = len(text)
    rgba_image = new_img.convert('RGBA')
    text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
    image_draw = ImageDraw.Draw(text_overlay)
    for i in range(0, rgba_image.size[0], font_len*40+50):
        for j in range(0, rgba_image.size[1], 70):
            image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 30))
    text_overlay = text_overlay.rotate(-45)
    image_with_text = Image.alpha_composite(rgba_image, text_overlay)
    # 裁切图片
    image_with_text = image_with_text.crop(
        (image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
    image_with_text.save(savefilename)


if __name__ == '__main__':
    path = r"d:\1"
    pathto = r"d:\2"
    txt = u'周口师范学院经济与管理学院'
    list = os.listdir(path)
    count = len(list)
    for i in range(1, count):
        imgname = list[i-1]
        print(i, count, imgname)
        add_text_to_image(os.path.join(
            path, imgname), txt, os.path.join(pathto, imgname))
